package com.starblink.store.storelink.ui

import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.toastSuccess
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.common.databinding.ActivityStoreLinkBinding
import com.starblink.android.common.web.WebShowBackActivity
import com.starblink.android.common.web.dialog.WebMoreDialog
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.CommUtils
import com.starblink.rocketreserver.FetchMerchantWebByIdQuery
import com.starblink.rocketreserver.fragment.DealVOF
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 店铺外链页
 */
@Route(path = RoutePage.Store.PAGE_LINK)
class StoreLinkActivity : WebShowBackActivity<ActivityStoreLinkBinding, BaseViewModel>() {

    @Autowired
    @JvmField
    var couponCode: String? = null

    @Autowired
    @JvmField
    var discount: String? = null

    @Autowired
    @JvmField
    var prefix: String? = ""

    @Autowired
    @JvmField
    var suffix: String? = ""

    var idIsWrong: Boolean = false//从SuperDeal过来，id可能错误

    override fun initViewBinding(): ActivityStoreLinkBinding {
        return ActivityStoreLinkBinding.inflate(layoutInflater)
    }

    override fun initData() {
        super.initData()

        viewBinding.rlTop.ivWeb.setOnClickListener {
            //分享店铺链接
            clickFunShare()
            //使用浏览器打开
//            CommUtils.openUrlToWeb(mActivity, mWeburl)
        }

        if (storeId == null && intent.hasExtra(RoutePage.Store.ID)
        ) {
            storeId = intent.getStringExtra(RoutePage.Store.ID)
        }
        trackView()

        Log.e("couponCode", "===1==$storeId==$couponCode===$discount===$prefix===$suffix")
        if (storeId != null) {
            //获取店铺详情
//            storeId = "8_317471430431879169"
            lifecycleScope.launch(Dispatchers.IO) {
                val response = SkGqlClient.skQuery(
                    FetchMerchantWebByIdQuery(
                        storeId!!,
                    )
                )
                if (response?.data?.fetchMerchantWebById?.merchantWebVOF != null) {
                    lifecycleScope.launch(Dispatchers.Main) {
                        val merchantWeb = response.data!!.fetchMerchantWebById!!
                        storeId = merchantWeb.merchantWebVOF.id
                        storeName = merchantWeb.merchantWebVOF.merchantName
                        storeLogo = merchantWeb.merchantWebVOF.logo
                        subOrNot = merchantWeb.merchantWebVOF.subOrNot == true
                        setView()

                        //Coupon Code
                        dealList =
                            if (!discount.isNullOrEmpty()) {
                                listOf(
                                    DealVOF(
                                        DealVOF.DiscountInfo(
                                            discount,
                                            prefix,
                                            suffix
                                        ), couponCode
                                    )
                                )
                            } else {
                                merchantWeb.merchantWebVOF.dealInfoList?.mapNotNull { it?.dealVOF }
                                    ?: emptyList()
                            }
                        Log.e("couponCode", "===3==$dealList")

                        showBottomView()
                        trackView()
                    }
                } else {
                    Log.e("couponCode", "===2=====$discount===$prefix===$suffix===$couponCode")
                    idIsWrong = true
                    //Coupon Code id可能不是店铺id 兜底处理
                    lifecycleScope.launch(Dispatchers.Main) {
                        if (!discount.isNullOrEmpty()) {
                            dealList = listOf(
                                DealVOF(
                                    DealVOF.DiscountInfo(
                                        discount,
                                        prefix,
                                        suffix
                                    ), couponCode
                                )
                            )
                        }

                        showBottomView()
                        trackView()

                    }
                }
            }
        } else {
            if (!discount.isNullOrEmpty()) {
                dealList = listOf(
                    DealVOF(
                        DealVOF.DiscountInfo(
                            discount,
                            prefix,
                            suffix
                        ), couponCode
                    )
                )
            }

            showBottomView()
        }

        viewBinding.rlBottom.btnMore.setOnClickListener {
            //更多操作
            WebMoreDialog(
                false, subOrNot, idIsWrong = idIsWrong, clickFollowStore = {
                    //Follow 店铺
                    clickFollowStore(it)
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                pageDef,
                                SpmElementDef.StoreSub
                            ),
                            params = mapOf(
                                "merchantName" to (storeName ?: ""),
                            )
                                .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                                .plus("result" to if (subOrNot) "0" else "1")
                        )
                    )
                }, clickShare = {
                    //分享页面
                    clickFunShare()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                pageDef,
                                SpmElementDef.ShareClickSpm
                            ),
                            params = trackParams()
                        )
                    )
                },
                findSimilar = {}, priceCheck = {},
                copyLink = {
                    CommUtils.copyText(mWeburl)
                    toastSuccess("Copied Successfully!")
                },
                toWishList = {
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                pageDef,
                                SpmElementDef.Element_33070
                            ),
                            params = trackParams()
                        )
                    )
                }).show(supportFragmentManager, "product_info")
        }
        viewBinding.rlBottom.llOpenStore.setOnClickListener {
            //跳转浏览器
            CommUtils.openUrlToWeb(mActivity, mWeburl)
        }

    }

    override fun setPageEnf() {
        pageDef = SpmPageDef.StoreLinkPage
    }

    override fun onResume() {
        super.onResume()
        pageExposure(pageDef, params = trackParams())
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(pageDef, params = trackParams())
    }

    private fun clickFunShare() {
        appShare(mWeburl)
    }

    override fun trackView() {
        super.trackView()
    }

    override fun trackParams(): Map<String, String> {
        return mapOf("merchantName" to (storeName ?: ""))
    }
}